package com.mashibing.jvm.c3_jmm.writecombining;

/**
 * 合并写
 *
 * home 电脑结果：
 * 1 ->singleLoop duration(ns) 5023952506
 * 1 ->splitLoop  duration(ns) 4828675546
 * 2 ->singleLoop duration(ns) 5053063544
 * 2 ->splitLoop  duration(ns) 4816335033
 * 3 ->singleLoop duration(ns) 4897200832
 * 3 ->splitLoop  duration(ns) 5168790459
 */
public class WriteCombining {

    private static final int ITERATIONS = Integer.MAX_VALUE;
    private static final int ITEMS = 1 << 24;
    private static final int MASK = ITEMS - 1;

    private static final byte[] arrayA = new byte[ITEMS];
    private static final byte[] arrayB = new byte[ITEMS];
    private static final byte[] arrayC = new byte[ITEMS];
    private static final byte[] arrayD = new byte[ITEMS];
    private static final byte[] arrayE = new byte[ITEMS];
    private static final byte[] arrayF = new byte[ITEMS];
    private static final byte[] arrayG = new byte[ITEMS];
    private static final byte[] arrayH = new byte[ITEMS];

    public static void main(String[] args) {
        for (int i = 1; i < 4; i++) {
            System.out.println(i+ " ->singleLoop duration(ns) "+ runCaseOne());
            System.out.println(i+ " ->splitLoop  duration(ns) "+ runCaseTwo());
        }
    }
    
    public static long runCaseOne(){
        long start = System.nanoTime();
        int i = ITERATIONS;
        while (--i != 0){
            int slot = i & MASK;
            byte b = (byte)i;
            arrayA[slot] = b;
            arrayB[slot] = b;
            arrayC[slot] = b;
            arrayD[slot] = b;
            arrayE[slot] = b;
            arrayF[slot] = b;
            arrayG[slot] = b;
            // arrayH[slot] = b;
        }
        return System.nanoTime()-start;
    }

    public static long runCaseTwo(){
        long start = System.nanoTime();
        int i = ITERATIONS;
        while (--i != 0){
            int slot = i & MASK;
            byte b = (byte)i;
            arrayA[slot] = b;
            arrayB[slot] = b;
            arrayC[slot] = b;
            arrayD[slot] = b;
        }
        i = ITERATIONS;
        while (--i != 0){
            int slot = i & MASK;
            byte b = (byte)i;
            arrayE[slot] = b;
            arrayF[slot] = b;
            arrayG[slot] = b;
            arrayH[slot] = b;
        }
        return System.nanoTime()-start;
    }

}
